package cn.harry.cabinet.view.fragments

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ScrollView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.theme.manager.ThemeManager
import cn.harry.cabinet.utils.AppConfigKeys
import cn.harry.cabinet.utils.logConfigChange
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.security.MessageDigest

/**
 * 密码管理Fragment
 * 用于修改管理员密码
 */
class PasswordManagementFragment : BaseFragment() {
    
    companion object {
        private const val TAG = "PasswordManagement"
        private const val MIN_PASSWORD_LENGTH = 4
        private const val DEFAULT_PASSWORD = "1234"
    }
    
    private lateinit var tilCurrentPassword: TextInputLayout
    private lateinit var etCurrentPassword: TextInputEditText
    private lateinit var tilNewPassword: TextInputLayout
    private lateinit var etNewPassword: TextInputEditText
    private lateinit var tilConfirmPassword: TextInputLayout
    private lateinit var etConfirmPassword: TextInputEditText
    private lateinit var btnUpdatePassword: MaterialButton
    
    private lateinit var scrollView: ScrollView
    
    private lateinit var configRepository: ConfigurationRepository
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_password_management, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        initViews(view)
        initRepository()
        setupListeners()
        applyTheme()
    }
    
    private fun initViews(view: View) {
        scrollView = view.findViewById(R.id.scroll_view)
        tilCurrentPassword = view.findViewById(R.id.til_current_password)
        etCurrentPassword = view.findViewById(R.id.et_current_password)
        tilNewPassword = view.findViewById(R.id.til_new_password)
        etNewPassword = view.findViewById(R.id.et_new_password)
        tilConfirmPassword = view.findViewById(R.id.til_confirm_password)
        etConfirmPassword = view.findViewById(R.id.et_confirm_password)
        btnUpdatePassword = view.findViewById(R.id.btn_update_password)
    }
    
    private fun initRepository() {
        configRepository = ConfigurationRepository(requireActivity().application)
    }
    
    private fun setupListeners() {
        // 实时验证输入
        etNewPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateNewPassword()
            }
        })
        
        etConfirmPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                validateConfirmPassword()
            }
        })
        
        // 更新密码按钮
        btnUpdatePassword.setOnClickListener {
            updatePassword()
        }
    }
    
    /**
     * 验证新密码格式
     */
    private fun validateNewPassword(): Boolean {
        val password = etNewPassword.text.toString()
        
        return when {
            password.isEmpty() -> {
                tilNewPassword.error = null
                false
            }
            password.length < MIN_PASSWORD_LENGTH -> {
                tilNewPassword.error = "密码至少需要${MIN_PASSWORD_LENGTH}位字符"
                false
            }
            else -> {
                tilNewPassword.error = null
                true
            }
        }
    }
    
    /**
     * 验证确认密码
     */
    private fun validateConfirmPassword(): Boolean {
        val newPassword = etNewPassword.text.toString()
        val confirmPassword = etConfirmPassword.text.toString()
        
        return when {
            confirmPassword.isEmpty() -> {
                tilConfirmPassword.error = null
                false
            }
            newPassword != confirmPassword -> {
                tilConfirmPassword.error = "两次输入的密码不一致"
                false
            }
            else -> {
                tilConfirmPassword.error = null
                true
            }
        }
    }
    
    /**
     * 更新密码
     */
    private fun updatePassword() {
        val currentPassword = etCurrentPassword.text.toString()
        val newPassword = etNewPassword.text.toString()
        val confirmPassword = etConfirmPassword.text.toString()
        
        // 验证输入
        if (currentPassword.isEmpty()) {
            tilCurrentPassword.error = "请输入当前密码"
            return
        }
        
        if (newPassword.isEmpty()) {
            tilNewPassword.error = "请输入新密码"
            return
        }
        
        if (confirmPassword.isEmpty()) {
            tilConfirmPassword.error = "请确认新密码"
            return
        }
        
        if (!validateNewPassword()) {
            return
        }
        
        if (!validateConfirmPassword()) {
            return
        }
        
        // 禁用按钮，防止重复点击
        btnUpdatePassword.isEnabled = false
        
        lifecycleScope.launch {
            try {
                // 验证当前密码
                val storedPassword = withContext(Dispatchers.IO) {
                    getConfigValue(AppConfigKeys.TYPE_SECURITY, AppConfigKeys.ADMIN_PASSWORD)
                }
                
                val currentPasswordHash = hashPassword(currentPassword)
                val defaultPasswordHash = hashPassword(DEFAULT_PASSWORD)
                
                // 如果没有设置密码，使用默认密码验证
                val expectedPassword = if (storedPassword.isNullOrEmpty()) {
                    Log.i(TAG, "使用默认密码验证")
                    defaultPasswordHash
                } else {
                    storedPassword
                }
                
                if (expectedPassword != currentPasswordHash) {
                    // 当前密码错误
                    tilCurrentPassword.error = "当前密码错误"
                    Toast.makeText(requireContext(), "当前密码错误", Toast.LENGTH_SHORT).show()
                    btnUpdatePassword.isEnabled = true
                    
                    // 记录密码错误日志
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "PASSWORD_CHANGE",
                        description = "尝试修改管理员密码失败：当前密码错误",
                        oldValue = "密码验证",
                        newValue = "验证失败"
                    )
                    return@launch
                }
                
                // 保存新密码
                val newPasswordHash = hashPassword(newPassword)
                withContext(Dispatchers.IO) {
                    saveConfigValue(AppConfigKeys.TYPE_SECURITY, AppConfigKeys.ADMIN_PASSWORD, newPasswordHash)
                }
                
                Log.i(TAG, "管理员密码更新成功")
                Toast.makeText(requireContext(), "密码更新成功", Toast.LENGTH_SHORT).show()
                
                // 记录密码修改成功日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "PASSWORD_CHANGE",
                    description = "修改管理员密码成功",
                    oldValue = "密码已设置",
                    newValue = "密码已更新"
                )
                
                // 清空输入框
                etCurrentPassword.text?.clear()
                etNewPassword.text?.clear()
                etConfirmPassword.text?.clear()
                
                // 清除错误提示
                tilCurrentPassword.error = null
                tilNewPassword.error = null
                tilConfirmPassword.error = null
                
            } catch (e: Exception) {
                Log.e(TAG, "更新密码失败", e)
                Toast.makeText(requireContext(), "更新密码失败: ${e.message}", Toast.LENGTH_SHORT).show()
            } finally {
                btnUpdatePassword.isEnabled = true
            }
        }
    }
    
    /**
     * 获取配置值
     */
    private suspend fun getConfigValue(type: String, key: String): String? {
        val config = configRepository.getByTypeAndKey(type, key)
        return config?.value
    }
    
    /**
     * 保存配置值
     */
    private suspend fun saveConfigValue(type: String, key: String, value: String) {
        val existingConfig = configRepository.getByTypeAndKey(type, key)
        if (existingConfig != null) {
            // 更新现有配置
            configRepository.update(existingConfig.copy(value = value))
        } else {
            // 创建新配置
            val newConfig = cn.harry.cabinet.model.entity.Configuration(
                type = type,
                key = key,
                value = value
            )
            configRepository.create(newConfig)
        }
    }
    
    /**
     * 应用主题
     */
    private fun applyTheme() {
        lifecycleScope.launch {
            try {
                val theme = withContext(Dispatchers.IO) {
                    ThemeManager.loadThemeFromDatabase(requireContext())
                }
                
                // 根据主题设置背景色
                val backgroundColor = when (theme) {
                    ThemeManager.Theme.CHINA_RED -> ContextCompat.getColor(requireContext(), R.color.china_red_background)
                    ThemeManager.Theme.VIBRANT_ORANGE -> ContextCompat.getColor(requireContext(), R.color.vibrant_orange_background)
                    ThemeManager.Theme.TECH_BLUE -> ContextCompat.getColor(requireContext(), R.color.tech_blue_background)
                }
                
                scrollView.setBackgroundColor(backgroundColor)
                
            } catch (e: Exception) {
                Log.e(TAG, "应用主题失败", e)
            }
        }
    }
    
    /**
     * 密码哈希
     */
    private fun hashPassword(password: String): String {
        val bytes = MessageDigest.getInstance("SHA-256").digest(password.toByteArray())
        return bytes.joinToString("") { "%02x".format(it) }
    }
}